<?php
class Pageley_Tag_Echo extends Pageley_Tag_Abstract {
    
    private $text;
    private $truncate;
    private $escape;
    private $limitCharacters;
    
    public function execute() {
        $text = $this->applyLimitCharacters($this->text);
        if($this->escape) {
            echo htmlspecialchars($text);
        } else {
            echo $text;
        }
    }
    
    private function applyLimitCharacters($text) {
        $result = "";
        if($this->limitCharacters > 0) {
            if($this->truncate) {
                $result = $this->truncate($text);
            } else {
                $result = $this->limitLines($text);
            }
        } else {
            $result = $text;
        }
        return $result;
    }
    
    private function truncate($text) {
        $result = $text;
        if(Pageley_Util_String::length($text) > $this->limitCharacters) {
            $result = $this->limit($text);
            $result .= " ...";
        }
        return $result;
    }
    
    private function limitLines($text) {
        $result = "";
        $lines = Pageley_Util_String::split($text, "\n");
        foreach($lines as $line) {
            $remainder = $line;
            while(Pageley_Util_String::length($remainder) > $this->limitCharacters) {
                $fragment = $this->limit($remainder);
                $result .= $fragment . "\n  ";
                $length = Pageley_Util_String::length($fragment);
                $remainder = Pageley_Util_String::substring($remainder, $length);
            }
            $result .= $remainder . "\n";
        }
        return $result;
    }
    
    private function limit($text) {
        $length = $this->limitCharacters;
        $fragment = Pageley_Util_String::substring($text, 0, $length);
        $spacePos = Pageley_Util_String::lastIndexOf($fragment, " ");
        if($spacePos !== false) {
            $length = $spacePos + 1;
        }
        return Pageley_Util_String::substring($text, 0, $length);
    }
    
    public function setText($text) {
        $this->text = $text;
    }
    
    public function setEscape($escape) {
        $this->escape = $escape;
    }
    
    public function setTruncate($truncate) {
        $this->truncate = $truncate;
    }
    
    public function setLimitCharacters($limitCharacters) {
        $this->limitCharacters = $limitCharacters;
    }
}